<template>
  <div class="statistic">
    <div class="content-block topDiv">
      <img src="../../assets/images/Home/deviceIcon.png" />
      <p class="text">物联感知设备数</p>
      <p class="number">{{ totalNum }}<label>个</label></p>
    </div>
    <div class="content-block alarmDiv">
      <p class="title">告警及处置情况</p>
      <div class="changeTitle">
        <div
          :class="changeChart === 1 ? 'switch-on' : 'switch'"
          @click="changeValue(1)"
        >
          日
        </div>
        <div
          :class="changeChart === 2 ? 'switch-on' : 'switch'"
          @click="changeValue(2)"
          style="margin-left: 8px"
        >
          周
        </div>
        <div
          :class="changeChart === 3 ? 'switch-on' : 'switch'"
          @click="changeValue(3)"
          style="margin-left: 8px"
        >
          月
        </div>
      </div>
      <div v-if="chartData.length === 0" style="width: 100%;margin-top: 10ch;text-align: center;position: absolute;left: 0;">暂无数据</div>
      <canvas id="container1" class="container1"></canvas>
    </div>
    <div class="content-block rankDiv">
      <p class="title">设备告警易发排名</p>
      <rank-progress
        class="progress1"
        :rank-title="rankTitle[0]"
        :bar-data="barDataName"
      ></rank-progress>
      <rank-progress
        class="progress1"
        :rank-title="rankTitle[1]"
        :bar-data="barDataType"
      ></rank-progress>
      <!-- <rank-progress
        class="progress1"
        :rank-title="rankTitle[2]"
        :bar-data="barDataAddress"
      ></rank-progress> -->
    </div>
  </div>
</template>

<script>
// import _ from "lodash";
import rankProgress from "./components/RankProgress";
import {
  getMobileStatisticsOfIndex,
  getMobileStatisticsOfAlarm
} from "@/api/home";

export default {
  name: "overview",
  components: {
    rankProgress
  },
  data() {
    return {
      totalNum: sessionStorage.getItem("euqipmentCount"),
      changeChart: 1,
      timeScaleType: "日",
      savetotalValue: null,
      totalValue: {
        告警数: "",
        处置数: ""
      },
      chartData: [
        // {
        //   name: '告警数',
        //   deviceType: '消防栓',
        //   number: 18
        // }, {
        //   name: '告警数',
        //   deviceType: '地磁',
        //   number: 28
        // }, {
        //   name: '告警数',
        //   deviceType: '烟感',
        //   number: 39
        // }, {
        //   name: '告警数',
        //   deviceType: '视频',
        //   number: 49
        // },
        // {
        //   name: '处置数',
        //   deviceType: '消防栓',
        //   number: 12
        // }, {
        //   name: '处置数',
        //   deviceType: '地磁',
        //   number: 23
        // }, {
        //   name: '处置数',
        //   deviceType: '烟感',
        //   number: 34
        // }, {
        //   name: '处置数',
        //   deviceType: '视频',
        //   number: 44
        // }
      ],
      barDataName: [
        // {
        //   name: "烟感设备001",
        //   num: 20
        // },
        // {
        //   name: "烟感设备112",
        //   num: 50
        // },
        // {
        //   name: "烟感设备003",
        //   num: 70
        // },
        // {
        //   name: "烟感设备004",
        //   num: 110
        // }
      ],
      barDataType: [],
      barDataAddress: [],
      deviceList1: [],
      deviceList2: [],
      rankTitle: ["设备名称", "设备类型", "设备地点"]
    };
  },
  watch: {
    totalValue: {
      handler(v) {
        let vue = this;
        vue.$nextTick(() => {
          vue.drawCharts();
        });
      },
      deep: true
    },
    chartData: {
      handler(v) {
        let vue = this;
        vue.$nextTick(() => {
          vue.drawCharts();
        });
      },
      deep: true
    }
  },
  mounted() {
    this.$store.commit("setTopBg", "statistics-bg");
    let vue = this;
    vue.drawCharts();
    // this.getIndexData();
    this.getAlarmData(this.timeScaleType);
  },
  methods: {
    async getIndexData() {
      let res = await getMobileStatisticsOfIndex();
      if (res.code === 0) {
        this.totalNum = res.data.euqipmentCount;
      }
    },
    async getAlarmData(value) {
      let res = await getMobileStatisticsOfAlarm({
        timeScaleType: value
      });
      this.deviceList1 = [];
      this.deviceList2 = [];
      this.chartData = [];
      this.barDataName = [];
      this.barDataType = [];
      this.barDataAddress = [];
      if (res.code === 0) {
        this.totalValue.告警数 = 0; //res.data.alarnCountOfAll;
        this.totalValue.处置数 = 0; //res.data.alarnCountOfDone;
        res.data.alarmStatisticsList.forEach(item => {
          this.totalValue.告警数 += item.alarmCountOfAll || 0;
          this.deviceList1.push(
            Object.assign(
              {},
              { name: "告警数" },
              { deviceType: item.alarmTypeName },
              { number: item.alarmCountOfAll | 0 }
            )
          );
          this.totalValue.处置数 += item.alarmCountOfDONE || 0;
          this.deviceList2.push(
            Object.assign(
              {},
              { name: "处置数" },
              { deviceType: item.alarmTypeName },
              { number: item.alarmCountOfDONE | 0 }
            )
          );
        });
        this.chartData = this.deviceList1.concat(this.deviceList2);
        // res.data.rankByEquipName.forEach(item => {
        //   this.barDataName.push({
        //     name: item.equipmentNameOrTypeNameOrAddr,
        //     num: item.alarmCount
        //   });
        // });
        // res.data.rankByEquipTypeName.forEach(item => {
        //   this.barDataType.push({
        //     name: item.equipmentNameOrTypeNameOrAddr,
        //     num: item.alarmCount
        //   });
        // });
        // res.data.rankByAlarmAddr.forEach(item => {
        //   this.barDataAddress.push({
        //     name: item.equipmentNameOrTypeNameOrAddr,
        //     num: item.alarmCount
        //   });
        // });
        res.data.alarmStatisticsListOrderByType
          .sort((a, b) => b.alarmCountOfAll - a.alarmCountOfAll)
          .slice(0, 3)
          .forEach(item => {
            this.barDataType.push({
              name: item.alarmTypeName,
              num: item.alarmCountOfAll
            });
          });
        res.data.alarmStatisticsListOrderByname
          .sort((a, b) => b.alarmCountOfAll - a.alarmCountOfAll)
          .slice(0, 3)
          .forEach(item => {
            this.barDataName.push({
              name: item.alarmTypeName,
              num: item.alarmCountOfAll
            });
          });
        // res.data.rankByEquipTypeName.forEach(item => {
        //   this.barDataType.push({
        //     name: item.equipmentNameOrTypeNameOrAddr,
        //     num: item.alarmCount
        //   });
        // });
        // res.data.rankByAlarmAddr.forEach(item => {
        //   this.barDataAddress.push({
        //     name: item.equipmentNameOrTypeNameOrAddr,
        //     num: item.alarmCount
        //   });
        // });
      }
    },
    changeValue(num) {
      if (num === 1) {
        this.changeChart = 1;
        this.getAlarmData("日");
      } else if (num === 2) {
        this.changeChart = 2;
        this.getAlarmData("周");
      } else {
        this.changeChart = 3;
        this.getAlarmData("月");
      }
    },
    drawCharts() {
      let vue = this;
      // 创建Chart对象
      const chart = new this.$F2.Chart({
        id: "container1",
        pixelRatio: window.devicePixelRatio
      });
      if (vue.chartData.length===0) return
      // 载入数据
      chart.source(vue.chartData);
      // 图例
      chart.legend({
        position: "top",
        itemFormatter: function itemFormatter(val) {
          if (val.length === 3) {
            return val + "  " + vue.totalValue[val] + "个";
          }
          if (val.length === 4) {
            return (
              val.substring(0, 3) +
              "  " +
              vue.savetotalValue.find(e => e.name === val.substring(0, 3))
                .value +
              "个"
            );
          }
        }
      });
      // chart.tooltip({
      //   custom: true, // 自定义 tooltip 内容框
      //   onChange: function onChange(obj) {
      //     const legend = chart.get("legendController").legends.top[0];
      //     const tooltipItems = obj.items;
      //     const legendItems = legend.items;
      //     const map = {};
      //     legendItems.forEach(function(item) {
      //       map[item.name] = item;
      //     });
      //     tooltipItems.forEach(function(item) {
      //       const name = item.name;
      //       const value = item.value;
      //       if (map[name]) {
      //         map[name].value = value;
      //       }
      //     });
      //     console.log(Object.values(map), "?????");
      //     vue.savetotalValue = Object.values(map);
      //     // legend.setItems(Object.values(map));
      //   },
      //   onHide() {
      //     const legend = chart.get("legendController").legends.top[0];
      //     legend.setItems(chart.getLegendItems().country);
      //   }
      // });
      chart.legend("gender", {
        position: "right"
      });
      // 坐标轴文本旋转
      chart.axis("deviceType", {
        label: {
          rotate: -Math.PI / 4,
          textAlign: "end",
          textBaseline: "middle"
        }
      });
      // 绘制
      chart
        .interval()
        .position("deviceType*number")
        .color("name")
        .size(10)
        .adjust({
          type: "dodge", // 并列柱状图 堆叠：stack
          marginRatio: 0.05 // 设置分组间柱子的间距
        })
        .style("type", {
          radius: function radius() {
            return [5, 5, 0, 0];
          }
        })
        .color("name", [
          "l(0) 0:#FF89A5 1:#FC5A69",
          "l(0) 0:#87DFFF 1:#2EB0FC"
        ]); // 指定颜色

      // 渲染图表
      chart.render();
    }
  }
};
</script>

<style lang="scss" scoped>
.statistic {
  .topDiv {
    width: 80%;
    height: 15px;
    margin-left: auto;
    margin-right: auto;
    img {
      float: left;
      width: 27px;
      height: 27px;
      margin-top: -5px;
      margin-left: 10px;
    }
    .text {
      float: left;
      width: 50%;
      margin-left: 22px;
      font-size: 15px;
      font-weight: 500;
    }
    .number {
      float: left;
      font-size: 20px;
      font-weight: 600;
      margin-left: 5px;
      margin-top: -5px;
      label {
        font-size: 15px;
        font-weight: 500;
        margin-left: 10px;
      }
    }
  }
  .alarmDiv {
    width: 80%;
    height: 240px;
    margin-left: auto;
    margin-right: auto;
    background-image: url("../../assets/images/Home/background.png");
    background-repeat: no-repeat;
    background-size: 170px 170px;
    background-position: 165px 0;
    .title {
      position: relative;
      width: 60%;
      font-size: 18px;
      font-weight: 600;
    }
    .changeTitle {
      position: relative;
      z-index: 999;
      pointer-events: auto;
      width: 30%;
      font-size: 14px;
      font-weight: 400;
      margin-left: 75%;
      .switch-on {
        color: #fc5a69;
        float: left;
        cursor: pointer;
        display: inline;
        border-bottom: 2px solid #fc5a69;
      }
      .switch {
        color: #666666;
        float: left;
        cursor: pointer;
        display: inline;
      }
    }
    .container1 {
      position: relative;
      width: 100%;
      height: 200px;
    }
  }
  .rankDiv {
    width: 80%;
    // height: 510px;
    margin-left: auto;
    margin-right: auto;
    background-image: url("../../assets/images/Home/background.png");
    background-repeat: no-repeat;
    background-size: 170px 170px;
    background-position: 165px 0;
    .title {
      width: 60%;
      font-size: 18px;
      font-weight: 600;
    }
    .progress1 {
      margin-top: 18px;
    }
  }
}
</style>
